package org.example.back.service.advice;

import org.example.back.entity.user.UserSport;
import org.example.back.mapper.user.UserSportMapper;
import org.example.back.mapper.advice.UserSportAdviceMapper;
import org.example.back.service.healthassistant.HealthAssistantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class UserSportAdviceService {

    @Autowired
    private UserSportMapper userSportMapper;

    @Autowired
    private UserSportAdviceMapper userSportAdviceMapper;

    @Autowired
    private HealthAssistantService healthAssistantService;

    public String getDailyAdvice(Integer userId, LocalDate date) {
        String cached = userSportAdviceMapper.findAdvice(userId, "day", date);
        if (cached != null) return cached;

        List<UserSport> sports = userSportMapper.findUserSportByDate(userId, date);
        if (sports == null || sports.isEmpty()) {
            return "您在 " + date + " 没有记录运动信息，请保持运动习惯以获得个性化建议。";
        }

        StringBuilder sb = new StringBuilder("以下是您 ")
            .append(date).append(" 的运动记录：\n");
        for (UserSport sport : sports) {
            sb.append(String.format("类型：%s，时间：%s - %s，强度：%s，消耗热量：%.1f 千卡，备注：%s\n",
                sport.getSportType(), sport.getStartTime().toLocalTime(), sport.getEndTime().toLocalTime(),
                sport.getIntensity(), sport.getCalories(), sport.getNote()));
        }
        sb.append("请根据以上运动数据，提供专业、简明的运动建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
        userSportAdviceMapper.insertAdvice(userId, "day", date, advice);
        return advice;
    }

    public String getWeeklyAdvice(Integer userId) {
        LocalDate startOfWeek = LocalDate.now().minusDays(6);
        String cached = userSportAdviceMapper.findAdvice(userId, "week", startOfWeek);
        if (cached != null) return cached;

        List<Map<String, Object>> weekData = userSportMapper.findUserSportLastWeek(userId);
        if (weekData == null || weekData.isEmpty()) {
            return "过去七天未记录运动信息，建议您坚持锻炼，以便获取有效建议。";
        }

        StringBuilder sb = new StringBuilder("以下是您过去七天的运动汇总数据：\n");
        for (Map<String, Object> day : weekData) {
            sb.append(String.format("日期：%s，总时长：%.2f 小时，平均强度：%.2f，运动天数：%d，总消耗热量：%.1f 千卡\n",
                day.get("day"),
                getDouble(day.get("total_duration_hours")),
                getDouble(day.get("avg_intensity")),
                getInt(day.get("sport_days_count")),
                getDouble(day.get("total_calories"))));
        }
        sb.append("请基于以上数据，为您提供一份本周运动建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
        userSportAdviceMapper.insertAdvice(userId, "week", startOfWeek, advice);
        return advice;
    }

    public String getMonthlyAdvice(Integer userId) {
        LocalDate startOfMonth = LocalDate.now().withDayOfMonth(1);
        String cached = userSportAdviceMapper.findAdvice(userId, "month", startOfMonth);
        if (cached != null) return cached;

        List<Map<String, Object>> monthData = userSportMapper.findUserSportByWeekInMonth(userId);
        if (monthData == null || monthData.isEmpty()) {
            return "最近一个月没有运动数据，无法提供建议。请持续锻炼并记录运动情况。";
        }

        StringBuilder sb = new StringBuilder("以下是您过去一个月按周统计的运动信息：\n");
        for (Map<String, Object> week : monthData) {
            sb.append(String.format("第 %s 周：共记录 %d 次，总时长 %.2f 小时，总消耗 %.1f 千卡，平均强度 %.2f\n",
                week.get("week") != null ? week.get("week").toString() : "未知",
                getInt(week.get("sport_days_count")),
                getDouble(week.get("total_duration_hours")),
                getDouble(week.get("total_calories")),
                getDouble(week.get("avg_intensity"))));
        }
        sb.append("请基于以上统计信息，为您提供月度运动建议。");

        String advice = healthAssistantService.getAnswerFromLLM(sb.toString());
        userSportAdviceMapper.insertAdvice(userId, "month", startOfMonth, advice);
        return advice;
    }

    // 每天凌晨调用，删除所有“日”运动建议缓存
    public void cleanDailyAdviceCache() {
        userSportAdviceMapper.deleteAdviceByType("day");
    }

    // 用户更新运动数据时调用，删除所有“周”“月”运动建议缓存
    public void cleanWeekAndMonthAdviceCache(Integer userId) {
        userSportAdviceMapper.deleteAdviceByUserAndType(userId,"day");
        userSportAdviceMapper.deleteAdviceByUserAndType(userId,"week");
        userSportAdviceMapper.deleteAdviceByUserAndType(userId,"month");
    }

    private double getDouble(Object obj) {
        return obj instanceof Number ? ((Number) obj).doubleValue() : 0.0;
    }

    private int getInt(Object obj) {
        return obj instanceof Number ? ((Number) obj).intValue() : 0;
    }
}
